package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.activity.api.domain.ActivityCouponVo;
import com.probox.activity.api.domain.CouponQuery;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.CustomException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.entity.domain.customer.*;
import com.probox.common.entity.domain.system.SysDictData;
import com.probox.common.entity.mapper.customer.*;
import com.probox.common.entity.service.customer.*;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.entity.utils.DictUtils;
import com.probox.common.entity.vo.customer.*;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerLevel;
import com.probox.customer.api.domain.CustomerLevelOpenVo;
import com.probox.customer.api.domain.CustomerPrivilegeOpenVo;
import com.probox.order.api.domain.ProfitShareVo;
import com.probox.order.api.utils.WechatV3Payment;
import com.probox.wechat.api.domain.WechatAuthorizationInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户等级Service业务层处理
 *
 * @author zsy
 * @date 2021-05-27
 */
@Service
@Transactional
public class CustomerLevelServiceImpl extends ServiceImpl<CustomerLevelMapper, CustomerLevel> implements ICustomerLevelService {
    //客户等级mapper
    @Autowired
    private CustomerLevelMapper customerLevelMapper;
    //客户权益service
    @Autowired
    private CustomerPrivilegeServiceImpl customerPrivilegeService;

    //客户权益service
    @Autowired
    private CustomerPrivilegeMapper customerPrivilegeMapper;
    //等级权益赠送mapper
    @Autowired
    private LevelPrivileageGiveMapper levelPrivileageGiveMapper;
    //付费规则mapper
    @Autowired
    private PaymentRuleMapper paymentRuleMapper;
    //等级权益mapper
    @Autowired
    private LevelPrivilegeMapper levelPrivilegeMapper;

    @Autowired
    private CustomerFundMapper customerFundMapper;

    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;


    @Autowired
    private ILevelPrivileageGiveService privileageGiveService;

    //等级权益service
    @Autowired
    private ILevelPrivilegeService levelPrivilegeService;


    //订单远程调用
    @Autowired
    private IOrderInfoService orderInfoService;
    //客户等级关系mapper


    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    public RedisService redisService;


    @Autowired
    private ICustomerFundService customerFundService;



    @Autowired
    private WechatMiniService wechatMiniService;


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询客户等级
     *
     * @param levelId 客户等级ID
     * @return 客户等级
     */
    @Override
    public CustomerLevel selectCustomerLevelById(Long levelId) {
        return this.getById(levelId);
    }

    /**
     * 查询客户等级列表
     *
     * @param customerLevel 客户等级
     * @return 客户等级
     */
    @Override
    public List<CustomerLevel> queryList(CustomerLevel customerLevel) {
        QueryWrapper<CustomerLevel> queryWrapper = Wrappers.query();
        queryWrapper.eq("START_STATUS", "1");
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.orderByAsc("customer_Grade");
        return customerLevelMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerLevel> queryCustomerLevelList() {
        QueryWrapper<CustomerLevel> queryWrapper = Wrappers.query();
        queryWrapper.eq("START_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.orderByAsc("customer_Grade");
        return customerLevelMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerPrivilegeOpenVo> selectLevelAndRightsByUserId(Long customerUid) {
        return customerLevelMapper.selectLevelAndRightsByUserId(customerUid);
    }

    @Override
    public List<CustomerLevel> selectCustomerLevelAndRight(Long customerUid) {
        return customerLevelMapper.selectCustomerLevelAndRight(customerUid);
    }



    /**
     * 新增客户等级
     *
     * @param customerLevel 客户等级
     * @return 结果
     */
    @Override
    public boolean insertCustomerLevel(CustomerLevel customerLevel) {
        customerLevel.setCreateName(SecurityUtils.getUsername());
        customerLevel.setCreateUser(SecurityUtils.getUserId());
        customerLevel.setDataStatus("1");
        return this.save(customerLevel);

    }

    /**
     * 修改客户等级
     *
     * @param customerLevel 客户等级
     * @return 结果
     */
    @Override
    public boolean updateCustomerLevel(CustomerLevel customerLevel) {
        if (CustomerLevelStartTypeEnum.start.getKey().equals(customerLevel.getStartStatus())) {
            //满足条件绑定等级
            if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(customerLevel.getCustomerPattern())) {
                /*
                List<CustomerFund> fundList = customerFundMapper.selectFundListQuery(customerLevel.getMinScore(), customerLevel.getPerformance(), customerLevel.getFansNumber(), SecurityUtils.getPlatformId());
                for (CustomerFund fund : fundList) {
                    bindFreeLevelNew(fund.getCustomerUid(), customerLevel.getLevelId(), fund);
                    //删除绑定等级缓存
                    redisService.deleteObject(CachePrefix.CUSTOMER_BIND_LEVEL + fund.getCustomerUid());
                }*/
            }
        } else {
            /*
            if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(customerLevel.getCustomerPattern())) {
                QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>();
                customerInfoQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
                customerInfoQueryWrapper.ne("STATUS", DataStatus.delete.getKey());
                customerInfoQueryWrapper.select("CUSTOMER_UID");
                List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(customerInfoQueryWrapper);
                for (CustomerInfo info : customerInfoList) {
                    UpdateWrapper<CustomerLevelInfo> levelInfoUpdateWrapper = new UpdateWrapper<>();
                    levelInfoUpdateWrapper.eq("CUSTOMER_UID", info.getCustomerUid());
                    levelInfoUpdateWrapper.set("STATUS", DataStatus.delete.getKey());
                    customerLevelInfoService.update(levelInfoUpdateWrapper);
                    //删除绑定等级缓存
                    redisService.deleteObject(CachePrefix.CUSTOMER_BIND_LEVEL + info.getCustomerUid());
                }

            }*/
        }
        //更新等级客户数
        //customerLevel.setCustomerNumber(null);
        //updateLevelCustoemrCount(customerLevel.getLevelId());
        customerLevel.setUpdateTime(DateUtil.date());
        customerLevel.setUpdateUser(SecurityUtils.getUserId());
        customerLevel.setUpdateName(SecurityUtils.getUsername());
        return this.updateById(customerLevel);
    }

    /**
     * 批量删除客户等级
     *
     * @param levelIds 需要删除的客户等级ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerLevelByIds(Long[] levelIds) {
        UpdateWrapper<CustomerLevel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("LEVEL_ID", Arrays.asList(levelIds));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        return this.update(updateWrapper);
    }


    /**
     * 查询客户免费客户模式等级列表
     *
     * @return 结果
     */
    @Override
    public List<CustomerLeveListlVo> getLevelInfoList(CustomerLeveListlVo customerLeveListlVo, Integer pageNum, Integer pageSize) {
        Long platformId = SecurityUtils.getPlatformId();
        List<CustomerLeveListlVo> customerLevelVoList = customerLevelMapper.getLevelInfoList(customerLeveListlVo, platformId, pageNum, pageSize);
        return customerLevelVoList;
    }

    @Override
    public List<CustomerLeveListlVo> getPayLevelInfoList(CustomerLeveListlVo customerLevelVo, Integer pageSize, Integer pageNum) {
        Long PlatformUid = SecurityUtils.getPlatformId();
        List<CustomerLeveListlVo> customerLevelVoList = customerLevelMapper.getPayLevelInfoList(customerLevelVo, PlatformUid, pageSize, pageNum);
        for (CustomerLeveListlVo level : customerLevelVoList) {
            level.setPaymentRules(paymentRuleMapper.selectById(level.getRuleId()));
        }
        return customerLevelVoList;
    }

    @Override
    public CustomerLevelVo getlevelInfoDetail(Long levelId) {
        Long platformId = SecurityUtils.getPlatformId();
//        logger.info("=============查询等级id=>" + levelId + ",平台id为=>" + platformId + "=====等级信息");
        CustomerLevelVo customerLevelVo = customerLevelMapper.getlevelInfoDetail(levelId, platformId);
        List<CustomerPrivilegeVo> customerPrivileges = customerLevelVo.getCustomerPrivileges();
        List<CustomerLevelPrivleageVo> customerLevelPrivleageVoList = new ArrayList<>();
        List<Long> cpUidArray = new ArrayList<>();
        for (CustomerPrivilegeVo PrivilegeVo : customerPrivileges) {
            LevelPrivilegeVo levelPrivilegesVo = PrivilegeVo.getLevelPrivilegesVo();
            if (ObjectUtil.isEmpty(levelPrivilegesVo)) {
                continue;
            }
            CustomerLevelPrivleageVo levelPrivleageVo = new CustomerLevelPrivleageVo();
            levelPrivleageVo.setPrivleageId(levelPrivilegesVo.getPrivilegeUid());
            levelPrivleageVo.setPrivleageName(PrivilegeVo.getPrivleageName());
            levelPrivleageVo.setIsUpgrade(levelPrivilegesVo.getIsUpgrade());
            //展示名称
            String privilegeShowname = levelPrivilegesVo.getPrivilegeShowname();
            levelPrivleageVo.setPrivleageShowName(privilegeShowname);
            levelPrivleageVo.setPrivilegeValue(PrivilegeVo.getPrivilegeValue());
            levelPrivleageVo.setCustomerPrivilegeUid(PrivilegeVo.getCustomerPrivilegeUid());
            String privilegeStatus = PrivilegeVo.getPrivilegeStatus();
            if (DataStatus.invalid.getKey().equals(privilegeStatus)) {
                levelPrivleageVo.setPrivilegeStatus(false);
            }
            if (DataStatus.valid.getKey().equals(privilegeStatus)) {
                levelPrivleageVo.setPrivilegeStatus(true);
            }
            levelPrivleageVo.setIsGive(levelPrivilegesVo.getIsGiveType());
            levelPrivleageVo.setPlatformUnit(levelPrivilegesVo.getPlatformUnit());
            customerLevelPrivleageVoList.add(levelPrivleageVo);
            cpUidArray.add(levelPrivleageVo.getPrivleageId());
        }
        //查询权益id
        QueryWrapper<LevelPrivilege> LevelPrivilegeQuery = new QueryWrapper<>();
        LevelPrivilegeQuery.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        LevelPrivilegeQuery.eq("STATUS", 1);
        LevelPrivilegeQuery.select("PRIVILEGE_UID");
        List<LevelPrivilege> levelPrivileges = levelPrivilegeMapper.selectList(LevelPrivilegeQuery);
        Long[] lpUid = new Long[levelPrivileges.size()];
        for (int i = 0; i < levelPrivileges.size(); i++) {
            lpUid[i] = levelPrivileges.get(i).getPrivilegeUid();
        }
        Long[] cpUid = new Long[cpUidArray.size()];
        for (int i = 0; i < cpUidArray.size(); i++) {
            cpUid[i] = cpUidArray.get(i);
        }
        List<Long> privilegeIdList = compare(cpUid, lpUid);
        for (Long pid : privilegeIdList) {
            LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(pid);
            CustomerLevelPrivleageVo levelPrivleageVo = new CustomerLevelPrivleageVo();
            levelPrivleageVo.setPrivleageShowName(levelPrivilege.getPrivilegeShowname());
            levelPrivleageVo.setPrivleageName(levelPrivilege.getPrivilegeName());
            levelPrivleageVo.setIsUpgrade(levelPrivilege.getIsUpgrade());
            levelPrivleageVo.setPrivleageId(levelPrivilege.getPrivilegeUid());
            levelPrivleageVo.setPrivilegeStatus(false);
            levelPrivleageVo.setPrivilegeValue(null);
            levelPrivleageVo.setPlatformUnit(levelPrivilege.getPlatformUnit());
            levelPrivleageVo.setIsGive(levelPrivilege.getIsGiveType());
            levelPrivleageVo.setDiscountCouponList(null);
            levelPrivleageVo.setGiftList(null);
            customerLevelPrivleageVoList.add(levelPrivleageVo);
        }
        customerLevelVo.setCustomerLevelPrivleageVos(customerLevelPrivleageVoList);
        customerLevelVo.setCustomerPrivileges(null);
        return customerLevelVo;
    }

    /**
     * 查询免费客户模式详情(前端)
     *
     * @return 结果
     */
    @Override
    public CustomerLevelVo getlevelInfoDetailOpen(Long levelId, Long platformUid) {
        if (platformUid == null) {
            platformUid = Constants.DEFAULT_PLATFORM_ID;
        }
        logger.info("=============查询等级id=>" + levelId + ",平台id为=>" + platformUid + "=====等级信息");
        CustomerLevelVo customerLevelVo = customerLevelMapper.getlevelInfoDetailOpen(levelId, platformUid);
        if (customerLevelVo == null) {
            return customerLevelVo;
        }
        if (customerLevelVo.getPerformance() != null) {
            customerLevelVo.setPerformance(MoneyUtils.changeF2B2(customerLevelVo.getPerformance()));
        }
        if ("1".equals(customerLevelVo.getCustomerPattern())) {
            PaymentRule paymentRule = paymentRuleMapper.selectById(customerLevelVo.getRuleId());
            paymentRule.setPrice(MoneyUtils.changeF2B2(paymentRule.getPrice()));
            customerLevelVo.setPaymentRules(paymentRule);
        }
        List<CustomerPrivilegeVo> customerPrivileges = customerLevelVo.getCustomerPrivileges();
        List<CustomerLevelPrivleageVo> customerLevelPrivleageVoList = new ArrayList<>();
        List<Long> cpUidArray = new ArrayList<>();
        for (CustomerPrivilegeVo PrivilegeVo : customerPrivileges) {
            LevelPrivilegeVo levelPrivilegesVo = PrivilegeVo.getLevelPrivilegesVo();
            CustomerLevelPrivleageVo levelPrivleageVo = new CustomerLevelPrivleageVo();
            levelPrivleageVo.setPrivleageId(levelPrivilegesVo.getPrivilegeUid());
            levelPrivleageVo.setPrivleageName(PrivilegeVo.getPrivleageName());
            levelPrivleageVo.setIsUpgrade(levelPrivilegesVo.getIsUpgrade());
            //展示名称
            String privilegeShowname = levelPrivilegesVo.getPrivilegeShowname();
            levelPrivleageVo.setPrivleageShowName(privilegeShowname);
            levelPrivleageVo.setPrivilegeValue(PrivilegeVo.getPrivilegeValue());
            levelPrivleageVo.setCustomerPrivilegeUid(PrivilegeVo.getCustomerPrivilegeUid());
            String privilegeStatus = PrivilegeVo.getPrivilegeStatus();
            if ("0".equals(privilegeStatus)) {
                levelPrivleageVo.setPrivilegeStatus(false);
            }
            if ("1".equals(privilegeStatus)) {
                levelPrivleageVo.setPrivilegeStatus(true);
            }
            levelPrivleageVo.setIsGive(levelPrivilegesVo.getIsGiveType());
            levelPrivleageVo.setPlatformUnit(levelPrivilegesVo.getPlatformUnit());
            if ("1".equals(levelPrivilegesVo.getIsGiveType())) {
                String privilegeName = levelPrivilegesVo.getPrivilegeName();
                Long customerPrivilegeUid = PrivilegeVo.getCustomerPrivilegeUid();
                List<com.probox.customer.api.domain.LevelPrivileageGiveVo> levelPrivileageGives = levelPrivileageGiveMapper.selectPrivileageGiveList(privilegeName, customerPrivilegeUid);
                List<com.probox.customer.api.domain.LevelPrivileageGiveVo> giveInfoList = new ArrayList<>();
                for (com.probox.customer.api.domain.LevelPrivileageGiveVo givevo : levelPrivileageGives) {
                    //更新赠品总数
                    if (CustomerLevelPrivilegeEnum.gift.getKey().equals(givevo.getGiveType())) {

                    } else if (CustomerLevelPrivilegeEnum.coupon.getKey().equals(givevo.getGiveType())) {
                        ActivityCouponVo coupon = getCouponById(givevo.getGiveGiftId());
                        //更新优惠券总数
                        if (coupon != null) {
                            givevo.setGiveSumNumber(String.valueOf(coupon.getCouponNums()));
                        }
                    } else {
                        //continue;
                        //return null;
                    }
                    giveInfoList.add(givevo);
                }
                //levelPrivleageVo.setLevelPrivileageGives(giveInfoList);
            }
            customerLevelPrivleageVoList.add(levelPrivleageVo);
            cpUidArray.add(levelPrivleageVo.getPrivleageId());
        }


        customerLevelVo.setCustomerLevelPrivleageVos(customerLevelPrivleageVoList);
        customerLevelVo.setCustomerPrivileges(null);
        return customerLevelVo;
    }

    /**
     * 判断是否是正确的经验和等级
     *
     * @return
     */
    private Boolean checkScore(CustomerLeveListlVo customerLevelVo) {
        if (ObjectUtil.isNotEmpty(customerLevelVo.getMinScore()) && ObjectUtil.isNotEmpty(customerLevelVo.getCustomerGrade())) {
            //查询出比他高的等级
            QueryWrapper<CustomerLevel> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("data_status", DataStatus.delete.getKey());
            queryWrapper.gt("CUSTOMER_GRADE", customerLevelVo.getCustomerGrade());
            queryWrapper.orderByAsc("CUSTOMER_GRADE");
            queryWrapper.last(" limit 1");
            CustomerLevel customerLevel = customerLevelMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(customerLevel)) {
                if (customerLevelVo.getMinScore() > customerLevel.getMinScore()) {
                    throw new BaseException("当前等级的经验大于下一级经验,下一级经验为" + customerLevel.getMinScore());
                }
            }
            // 查询出比他低的等级
            queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("data_status", DataStatus.delete.getKey());
            queryWrapper.lt("CUSTOMER_GRADE", customerLevelVo.getCustomerGrade());
            queryWrapper.orderByAsc("CUSTOMER_GRADE");
            queryWrapper.last(" limit 1");
            customerLevel = customerLevelMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(customerLevel)) {
                if (customerLevelVo.getMinScore() < customerLevel.getMinScore()) {
                    throw new BaseException("当前等级的经验小于上一级经验,上一级经验为" + customerLevel.getMinScore());
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 新的客户等级添加
     *
     * @param customerLevelVo
     * @return
     */
    @Override
    public boolean saveLevelPrivileageInfoNew(CustomerLeveListlVo customerLevelVo) {
        //公共参数
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        Long platformId = SecurityUtils.getPlatformId();
        HashMap dictCacheMap = DictUtils.getDictCacheMap("customer_privilege_update");
        // 判断等级所需要经验是否是正确的
        //if (checkScore(customerLevelVo)) {
           // throw new BaseException("数据有误,经验和等级不能为空！");
        //}
        //新增客户等级
        CustomerLevel customerLevel = new CustomerLevel();
        customerLevel.setCustomerGrade(customerLevelVo.getCustomerGrade());
        customerLevel.setPlatformId(platformId);
        customerLevel.setCustomerPattern(customerLevelVo.getCustomerPattern());
        customerLevel.setLevelName(customerLevelVo.getLevelName());
        customerLevel.setLevelIcon(customerLevelVo.getLevelIcon());
        customerLevel.setLevelIconNo(customerLevelVo.getLevelIconNo());
        customerLevel.setLevelIconItalic(customerLevelVo.getLevelIconItalic());
        customerLevel.setCaedFace(customerLevelVo.getCaedFace());
        customerLevel.setLevelColor(customerLevelVo.getLevelColor());
        customerLevel.setLevelImage(customerLevelVo.getLevelImage());
        customerLevel.setDataStatus(DataStatus.valid.getKey());
        customerLevel.setStartStatus(DataStatus.invalid.getKey());
        customerLevel.setMinScore(customerLevelVo.getMinScore());
        customerLevel.setFansNumber(0);
        customerLevel.setPerformance(BigDecimal.ZERO);
        customerLevel.setCreateTime(date);
        customerLevel.setCreateUser(userId);
        customerLevel.setCreateName(username);
        boolean save = this.save(customerLevel);
        if (save) {
            //新增客户权益
            customerLevelVo.getCustomerPrivileges().forEach(customerPrivilege -> {
                if ("false".equals(customerPrivilege.getPrivilegeStatus())) {
                    customerPrivilege.setPrivilegeStatus(DataStatus.invalid.getKey());
                } else {
                    customerPrivilege.setPrivilegeStatus(DataStatus.valid.getKey());
                }
                customerPrivilege.setPlatformId(platformId);
                Long privilegeUid = customerPrivilege.getPrivleageId();
                customerPrivilege.setPrivilegeUid(privilegeUid);
                customerPrivilege.setLevelUid(customerLevel.getLevelId());
                customerPrivilege.setCreateName(username);
                customerPrivilege.setCreateTime(date);
                customerPrivilege.setCreateUser(userId);
                customerPrivilege.setDataStatus(DataStatus.valid.getKey());
                if (ObjectUtil.isNotEmpty(dictCacheMap.get(customerPrivilege.getPrivleageName()))) {
                    customerPrivilege.setIsUpgrade(DataStatus.valid.getKey());
                } else {
                    customerPrivilege.setIsUpgrade(DataStatus.invalid.getKey());
                }
                boolean add = customerPrivilegeService.save(customerPrivilege);
                if (add) {
                    //使用权益后把权益状态改成使用中
                    LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(privilegeUid);
                    if (DataStatus.valid.getKey().equals(levelPrivilege.getPrivilegeStatus())) {
                        levelPrivilege.setPrivilegeStatus(DataStatus.valid.getKey());
                        levelPrivilegeMapper.updateById(levelPrivilege);
                    }
                    // 有用的等级才行
                    String nameByKey = CustomerPrivilegeValEnum.getNameByKey(customerPrivilege.getPrivleageName());
                    if (CustomerLevelStartTypeEnum.start.getKey().equals(customerPrivilege.getPrivilegeStatus()) &&
                            ObjectUtil.isNotEmpty(nameByKey)) {
                        if (CollectionUtil.isNotEmpty(customerPrivilege.getLevelPrivileageGives())) {
                            customerPrivilege.getLevelPrivileageGives().forEach(gives -> {
                                LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                                Long customerPrivilegeUid = customerPrivilege.getCustomerPrivilegeUid();
                                levelPrivileageGive.setPrivileageId(customerPrivilegeUid);
                                levelPrivileageGive.setGiveGiftId(gives.getGiveGiftId());
                                levelPrivileageGive.setGiveType(gives.getGiveType());
                                levelPrivileageGive.setGiveSumNumber(gives.getGiveSumNumber());
                                levelPrivileageGive.setGiveNumber(gives.getGiveNumber());
                                levelPrivileageGive.setGiveName(gives.getGiveName());
                                levelPrivileageGive.setCreateName(username);
                                levelPrivileageGive.setCreateUser(userId);
                                levelPrivileageGive.setCreateTime(date);
                                levelPrivileageGive.setStatus(DataStatus.valid.getKey());
                                levelPrivileageGiveMapper.insert(levelPrivileageGive);
                            });
                        }


                    }
                }
            });
        }
        return save;
    }

    /**
     * 新的 修改权益
     *
     * @param customerLevelVo
     * @return
     */
    @Override
    public boolean updateLevelPrivileageInfoNew(CustomerLeveListlVo customerLevelVo) {
        HashMap dictCacheMap = DictUtils.getDictCacheMap("customer_privilege_update");
        CustomerLevel level = this.getById(customerLevelVo.getLevelId());
        if (ObjectUtil.isEmpty(level)) throw new BaseException("数据不存在");
        //公共参数
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        Long platformId = SecurityUtils.getPlatformId();
        // 判断等级所需要经验是否是正确的
        //if (checkScore(customerLevelVo)) {
            //throw new BaseException("数据有误,经验和等级不能为空！");
        //}
        //新增客户等级
        CustomerLevel customerLevel = new CustomerLevel();
        customerLevel.setLevelId(level.getLevelId());
        customerLevel.setPlatformId(platformId);
        customerLevel.setCustomerGrade(customerLevelVo.getCustomerGrade());
        customerLevel.setCustomerPattern(customerLevelVo.getCustomerPattern());
        customerLevel.setLevelName(customerLevelVo.getLevelName());
        customerLevel.setLevelIcon(customerLevelVo.getLevelIcon());
        customerLevel.setLevelIconItalic(customerLevelVo.getLevelIconItalic());
        customerLevel.setLevelIconNo(customerLevelVo.getLevelIconNo());
        customerLevel.setLevelBanner(customerLevelVo.getLevelBanner());
        customerLevel.setCaedFace(customerLevelVo.getCaedFace());
        customerLevel.setLevelColor(customerLevelVo.getLevelColor());
        customerLevel.setLevelImage(customerLevelVo.getLevelImage());

        customerLevel.setDataStatus(DataStatus.valid.getKey());
        //customerLevel.setStartStatus(DataStatus.invalid.getKey());
        customerLevel.setMinScore(customerLevelVo.getMinScore());
        customerLevel.setCreateTime(date);
        customerLevel.setCreateUser(userId);
        customerLevel.setCreateName(username);
        boolean save = this.updateById(customerLevel);
        if (save) {
            //新增客户权益
            customerLevelVo.getCustomerPrivileges().forEach(customerPrivilege -> {
                if ("false".equals(customerPrivilege.getPrivilegeStatus())) {
                    customerPrivilege.setPrivilegeStatus(DataStatus.invalid.getKey());
                } else {
                    customerPrivilege.setPrivilegeStatus(DataStatus.valid.getKey());
                }
                customerPrivilege.setPlatformId(platformId);
                Long privilegeUid = customerPrivilege.getPrivleageId();
                customerPrivilege.setPrivilegeUid(privilegeUid);
                customerPrivilege.setLevelUid(customerLevel.getLevelId());
                customerPrivilege.setCreateName(username);
                customerPrivilege.setCreateTime(date);
                customerPrivilege.setCreateUser(userId);
                customerPrivilege.setDataStatus(DataStatus.valid.getKey());
                if (ObjectUtil.isNotEmpty(dictCacheMap.get(customerPrivilege.getPrivleageName()))) {
                    customerPrivilege.setIsUpgrade(DataStatus.valid.getKey());
                } else {
                    customerPrivilege.setIsUpgrade(DataStatus.invalid.getKey());
                }
                boolean result = false;
                if (ObjectUtil.isNotEmpty(customerPrivilege.getCustomerPrivilegeUid())) {
                    result = customerPrivilegeService.updateById(customerPrivilege);

                } else {
                    result = customerPrivilegeService.save(customerPrivilege);

                }
                if (result) {
                    //使用权益后把权益状态改成使用中
                    LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(customerPrivilege.getPrivilegeUid());
                    if (DataStatus.valid.getKey().equals(levelPrivilege.getPrivilegeStatus())) {
                        levelPrivilege.setPrivilegeStatus(DataStatus.valid.getKey());
                        levelPrivilegeMapper.updateById(levelPrivilege);
                    }
                    // 有用的等级才行
                    String nameByKey = CustomerPrivilegeValEnum.getNameByKey(customerPrivilege.getPrivleageName());
                    privileageGiveService.deleteLevelPrivileageGiveByIds(customerPrivilege.getCustomerPrivilegeUid());
                    if (CustomerLevelStartTypeEnum.start.getKey().equals(customerPrivilege.getPrivilegeStatus()) &&
                            ObjectUtil.isNotEmpty(nameByKey)) {
                        if (CollectionUtil.isNotEmpty(customerPrivilege.getLevelPrivileageGives())) {
                            customerPrivilege.getLevelPrivileageGives().forEach(gives -> {
                                LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                                Long customerPrivilegeUid = customerPrivilege.getCustomerPrivilegeUid();
                                levelPrivileageGive.setPrivileageId(customerPrivilegeUid);
                                levelPrivileageGive.setGiveGiftId(gives.getGiveGiftId());
                                levelPrivileageGive.setGiveType(gives.getGiveType());
                                levelPrivileageGive.setGiveSumNumber(gives.getGiveSumNumber());
                                levelPrivileageGive.setGiveNumber(gives.getGiveNumber());
                                levelPrivileageGive.setGiveName(gives.getGiveName());
                                levelPrivileageGive.setCreateName(username);
                                levelPrivileageGive.setCreateUser(userId);
                                levelPrivileageGive.setCreateTime(date);
                                levelPrivileageGive.setStatus(DataStatus.valid.getKey());
                                levelPrivileageGiveMapper.insert(levelPrivileageGive);
                            });
                        }

                    }
                }


            });
        }
        return save;
    }

    /**
     * old老的
     *
     * @param customerLevelVo
     * @return
     */
    @Override
    public boolean saveLevelPrivileageInfo(CustomerLeveListlVo customerLevelVo) {
        //公共参数
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        Long platformId = SecurityUtils.getPlatformId();
        //分拥
        BigDecimal directPointsPointsStr = customerLevelVo.getDirectPointsPointsStr();
        BigDecimal indirectPointsPointsStr = customerLevelVo.getIndirectPointsPointsStr();
        BigDecimal selfbuyPointsPointsStr = customerLevelVo.getSelfbuyPointsPointsStr();

        //判断比例是否大于最大分账比例
        WechatAuthorizationInfoVo wechatAuthorizationInfoVo = new WechatAuthorizationInfoVo();
        wechatAuthorizationInfoVo.setPlatformId(String.valueOf(platformId));
        wechatAuthorizationInfoVo.setAuthorizerType(WechatAuthorizationTypeEnum.applet.getKey());

        WechatAuthorizationInfoVo authorizationInfo = wechatMiniService.getAuthorizationInfoByPlatform(wechatAuthorizationInfoVo);
        if (authorizationInfo.getMerchantId() != null) {
            ProfitShareVo vo = new ProfitShareVo();
            vo.setSub_mchid(authorizationInfo.getMerchantId());
            ProfitShareVo profitShare = null;
            try {
                profitShare = WechatV3Payment.V3ProfitsharingMerchantConfigs(vo);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(e.getMessage());
            }
            if (profitShare.getMax_ratio() != null) {
                BigDecimal Points = directPointsPointsStr.add(indirectPointsPointsStr).add(selfbuyPointsPointsStr);
                if (profitShare.getMax_ratio() < Integer.parseInt(String.valueOf(Points))) {
                    throw new CustomException("分拥比例之和不能大于最大分账比例");
                }
            }
        }

        //新增客户等级
        CustomerLevel customerLevel = new CustomerLevel();
        customerLevel.setPlatformId(platformId);
        QueryWrapper<CustomerLevel> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("CUSTOMER_PATTERN", customerLevelVo.getCustomerPattern());
        queryWrapper.orderByDesc("CUSTOMER_GRADE").last("limit 1");
        queryWrapper.select("CUSTOMER_GRADE");
        CustomerLevel levelGrade = customerLevelMapper.selectOne(queryWrapper);
        if (levelGrade != null) {
            Integer customerGrade = levelGrade.getCustomerGrade();
            customerGrade = customerGrade + 1;
            customerLevel.setCustomerGrade(customerGrade);
        } else {
            customerLevel.setCustomerGrade(1);
        }
        customerLevel.setCustomerPattern(customerLevelVo.getCustomerPattern());
        customerLevel.setLevelName(customerLevelVo.getLevelName());
        customerLevel.setLevelIcon(customerLevelVo.getLevelIcon());
        String caedFace = customerLevelVo.getCaedFace();
        customerLevel.setCaedFace(caedFace);
        if ("0".equals(caedFace)) {
            customerLevel.setLevelColor(customerLevelVo.getLevelColor());
        } else if ("1".equals(caedFace)) {
            customerLevel.setLevelImage(customerLevelVo.getLevelImage());
        } else {
            return false;
        }
        customerLevel.setDataStatus(DataStatus.valid.getKey());
        customerLevel.setStartStatus("0");
        //等级分拥比例
//        customerLevel.setDirectPointsPoints(changeF2B2(customerLevelVo.getDirectPointsPoints()));
//        customerLevel.setIndirectPointsPoints(changeF2B2(customerLevelVo.getIndirectPointsPoints()));
//        customerLevel.setSelfbuyPointsPoints(changeF2B2(customerLevelVo.getSelfbuyPointsPoints()));

        //判断是否为付费客户模式
        if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevelVo.getCustomerPattern())) {
            PaymentRule paymentRule = customerLevelVo.getPaymentRules();
            StringBuilder payruleId = new StringBuilder();
            paymentRule.setPrice(MoneyUtils.changeY2B(paymentRule.getPrice()));
            paymentRule.setPlatformId(platformId);
            String periodValidity = paymentRule.getPeriodValidity();
            if (CustomerPayRuleTypeEnum.twelveMonth.getValue().equals(paymentRule.getPeriodValidity())) {
                paymentRule.setPeriodValidityNumber(365);
            } else {
                String substring = periodValidity.substring(0, periodValidity.length() - 2);
                paymentRule.setPeriodValidityNumber(Integer.parseInt(substring) * 30);
            }

            paymentRule.setCreateName(username);
            paymentRule.setCreateTime(date);
            paymentRule.setCreateUser(userId);
            paymentRuleMapper.insert(paymentRule);
            Long ruleId = paymentRule.getRuleId();
            payruleId.append(ruleId);
            customerLevel.setRuleId(String.valueOf(payruleId));
        } else {
            customerLevel.setMinScore(customerLevelVo.getMinScore());
            customerLevel.setFansNumber(customerLevelVo.getFansNumber());
            customerLevel.setPerformance(MoneyUtils.changeY2B(customerLevelVo.getPerformance()));
        }
        customerLevel.setCreateTime(date);
        customerLevel.setCreateUser(userId);
        customerLevel.setCreateName(username);
        this.save(customerLevel);
        //新增客户权益
        List<CustomerPrivilegeVo> customerPrivileges = customerLevelVo.getCustomerPrivileges();
        for (CustomerPrivilegeVo customerPrivilege : customerPrivileges) {
            customerPrivilege.setPlatformId(platformId);
            Long privilegeUid = customerPrivilege.getPrivleageId();
            customerPrivilege.setPrivilegeUid(privilegeUid);
            customerPrivilege.setLevelUid(customerLevel.getLevelId());
            customerPrivilege.setCreateName(username);
            customerPrivilege.setCreateTime(date);
            customerPrivilege.setCreateUser(userId);
            customerPrivilege.setDataStatus("1");
            if ("false".equals(customerPrivilege.getPrivilegeStatus())) {
                customerPrivilege.setPrivilegeStatus("0");
            } else {
                customerPrivilege.setPrivilegeStatus("1");
            }

            customerPrivilegeService.save(customerPrivilege);
            //使用权益后把权益状态改成使用中
            LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(privilegeUid);
            if ("1".equals(levelPrivilege.getPrivilegeStatus())) {
                levelPrivilege.setPrivilegeStatus("1");
                levelPrivilegeMapper.updateById(levelPrivilege);
            }
            if (CustomerPrivilegeValEnum.freeGift.getValue().equals(customerPrivilege.getPrivilegeValue()) && CustomerLevelStartTypeEnum.start.getKey().equals(customerPrivilege.getPrivilegeStatus())) {
                List<LevelPrivileageGiveVo> levelPrivileageGives = customerPrivilege.getLevelPrivileageGives();
                for (LevelPrivileageGiveVo gives : levelPrivileageGives) {
                    LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                    Long customerPrivilegeUid = customerPrivilege.getCustomerPrivilegeUid();
                    levelPrivileageGive.setPrivileageId(customerPrivilegeUid);
                    levelPrivileageGive.setGiveGiftId(gives.getGiveGiftId());
                    levelPrivileageGive.setGiveType(gives.getGiveType());
                    levelPrivileageGive.setGiveSumNumber(gives.getGiveSumNumber());
                    levelPrivileageGive.setGiveNumber(gives.getGiveNumber());
                    levelPrivileageGive.setGiveName(gives.getGiveName());
                    levelPrivileageGive.setCreateName(username);
                    levelPrivileageGive.setCreateUser(userId);
                    levelPrivileageGive.setCreateTime(date);
                    levelPrivileageGive.setStatus("1");
                    levelPrivileageGiveMapper.insert(levelPrivileageGive);
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateLevelPrivileage(CustomerLeveListlVo customerLevelVo) {
        CustomerLevel level = this.getById(customerLevelVo.getLevelId());
        //公共参数
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        Long platformId = SecurityUtils.getPlatformId();
        //分拥
        BigDecimal directPointsPointsStr = customerLevelVo.getDirectPointsPointsStr();
        BigDecimal indirectPointsPointsStr = customerLevelVo.getIndirectPointsPointsStr();
        BigDecimal selfbuyPointsPointsStr = customerLevelVo.getSelfbuyPointsPointsStr();

        //判断比例是否大于最大分账比例
        WechatAuthorizationInfoVo wechatAuthorizationInfoVo = new WechatAuthorizationInfoVo();
        wechatAuthorizationInfoVo.setPlatformId(String.valueOf(platformId));
        wechatAuthorizationInfoVo.setAuthorizerType(WechatAuthorizationTypeEnum.applet.getKey());
        WechatAuthorizationInfoVo authorizationInfo = wechatMiniService.getAuthorizationInfoByPlatform(wechatAuthorizationInfoVo);
        if (authorizationInfo.getMerchantId() != null) {
            ProfitShareVo vo = new ProfitShareVo();
            vo.setSub_mchid(authorizationInfo.getMerchantId());
            ProfitShareVo profitShare = null;
            try {
                profitShare = WechatV3Payment.V3ProfitsharingMerchantConfigs(vo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (profitShare.getMax_ratio() != null) {
                BigDecimal Points = directPointsPointsStr.add(indirectPointsPointsStr).add(selfbuyPointsPointsStr);
                if (profitShare.getMax_ratio() < Integer.parseInt(String.valueOf(Points))) {
                    throw new CustomException("分拥比例之和不能大于最大分账比例");
                }
            }
        }

        //修改客户等级
        CustomerLevel customerLevel = new CustomerLevel();
        customerLevel.setLevelId(customerLevelVo.getLevelId());
        customerLevel.setLevelName(customerLevelVo.getLevelName());
        customerLevel.setLevelIcon(customerLevelVo.getLevelIcon());
        String caedFace = customerLevelVo.getCaedFace();
        customerLevel.setCaedFace(caedFace);
        if ("0".equals(caedFace)) {
            customerLevel.setLevelColor(customerLevelVo.getLevelColor());
            customerLevel.setLevelImage(null);
        } else if ("1".equals(caedFace)) {
            customerLevel.setLevelImage(customerLevelVo.getLevelImage());
            customerLevel.setLevelColor(null);
        } else {
            return false;
        }
        //判断是否为付费客户模式
        if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevelVo.getCustomerPattern())) {
            PaymentRule paymentRule = customerLevelVo.getPaymentRules();
            StringBuilder payruleId = new StringBuilder();
            paymentRule.setPrice(MoneyUtils.changeY2B(paymentRule.getPrice()));
            paymentRule.setPlatformId(platformId);
            String periodValidity = paymentRule.getPeriodValidity();
            String substring = periodValidity.substring(0, periodValidity.length() - 2);
            paymentRule.setPeriodValidityNumber(Integer.parseInt(substring) * 30);
            paymentRule.setCreateName(username);
            paymentRule.setCreateTime(date);
            paymentRule.setCreateUser(userId);
            paymentRuleMapper.insert(paymentRule);
            payruleId.append(paymentRule.getRuleId());
            customerLevel.setRuleId(String.valueOf(payruleId));
        } else {
            customerLevel.setMinScore(customerLevelVo.getMinScore());
            customerLevel.setFansNumber(customerLevelVo.getFansNumber());
            customerLevel.setPerformance(MoneyUtils.changeY2B(customerLevelVo.getPerformance()));
        }
        customerLevel.setPlatformId(platformId);
        //等级分拥比例
//        BigDecimal Hundred = new BigDecimal("100");
//        BigDecimal directPointsPointsDivide = customerLevelVo.getDirectPointsPoints().divide(Hundred);
        customerLevel.setDirectPointsPoints(changeF2B2(customerLevelVo.getDirectPointsPoints()));
        customerLevel.setIndirectPointsPoints(changeF2B2(customerLevelVo.getIndirectPointsPoints()));
        customerLevel.setSelfbuyPointsPoints(changeF2B2(customerLevelVo.getSelfbuyPointsPoints()));

        customerLevel.setUpdateName(username);
        customerLevel.setUpdateTime(date);
        customerLevel.setUpdateUser(userId);
        this.updateById(customerLevel);
        //修改客户权益
        List<CustomerPrivilegeVo> customerPrivileges = customerLevelVo.getCustomerPrivileges();
        for (CustomerPrivilegeVo customerPrivilege : customerPrivileges) {
            CustomerPrivilege privileg = customerPrivilegeService.getById(customerPrivilege.getCustomerPrivilegeUid());
            if (privileg != null) {
                if ("true".equals(customerPrivilege.getPrivilegeStatus())) {
                    privileg.setPrivilegeStatus("1");
                } else {
                    privileg.setPrivilegeStatus("0");
                }
//                if ("false".equals(customerPrivilege.getPrivilegeStatus())) {
//
//                }
                privileg.setPrivilegeValue(customerPrivilege.getPrivilegeValue());
                privileg.setUpdateName(username);
                privileg.setUpdateTime(date);
                privileg.setUpdateUser(userId);

                customerPrivilegeService.updateById(privileg);

                //判断该权益是否还有等级在使用
                LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(privileg.getPrivilegeUid());
                String privilegeName = levelPrivilege.getPrivilegeName();
                LevelPrivilegeVo levelPrivilegeVo = levelPrivilegeService.getprivilegeLevelInfo(privilegeName);
                if (levelPrivilegeVo != null) {
                    if (StringUtils.isEmpty(levelPrivilegeVo.getLevelName())) {
                        levelPrivilege.setPrivilegeStatus("0");
                        levelPrivilegeMapper.updateById(levelPrivilege);
                    }
                }
                if (CustomerPrivilegeValEnum.freeGift.getValue().equals(privileg.getPrivilegeValue())) {
                    if ("1".equals(privileg.getPrivilegeStatus())) {
                        List<LevelPrivileageGiveVo> levelPrivileageGives = customerPrivilege.getLevelPrivileageGives();
                        Long[] giveGiftids = new Long[levelPrivileageGives.size()];
                        for (int i = 0; i < levelPrivileageGives.size(); i++) {
                            if (privilegeName.equals(levelPrivileageGives.get(i).getGiveType())) {
                                giveGiftids[i] = levelPrivileageGives.get(i).getGiveGiftId();
                            }
                        }
                        QueryWrapper<LevelPrivileageGive> queryWrappergive = new QueryWrapper<>();
                        queryWrappergive.eq("PRIVILEAGE_ID", privileg.getCustomerPrivilegeUid());
                        queryWrappergive.eq("GIVE_TYPE", privilegeName);
                        List<LevelPrivileageGive> PrivileageGive = levelPrivileageGiveMapper.selectList(queryWrappergive);
                        Long[] giveGiftidsdb = new Long[PrivileageGive.size()];
                        for (int i = 0; i < PrivileageGive.size(); i++) {
                            giveGiftidsdb[i] = PrivileageGive.get(i).getGiveGiftId();
                        }
                        List<Long> giveIds = compare(giveGiftids, giveGiftidsdb);
                        //判断不相同则删除或新增
                        for (Long id : giveIds) {
                            if (PrivileageGive.size() != 0) {
                                for (LevelPrivileageGive privileageGive : PrivileageGive) {
                                    if (!id.equals(privileageGive.getGiveGiftId())) {
                                        for (int i = 0; i < giveGiftids.length; i++) {
                                            if (id.equals(giveGiftids[i])) {
                                                LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                                                Long customerPrivilegeUid = customerPrivilege.getCustomerPrivilegeUid();
                                                levelPrivileageGive.setPrivileageId(customerPrivilegeUid);
                                                levelPrivileageGive.setGiveGiftId(id);
                                                levelPrivileageGive.setGiveType(privilegeName);
                                                levelPrivileageGive.setCreateName(username);
                                                levelPrivileageGive.setCreateUser(userId);
                                                levelPrivileageGive.setCreateTime(date);
                                                levelPrivileageGive.setStatus("1");
                                                levelPrivileageGiveMapper.insert(levelPrivileageGive);
                                            }
                                        }
                                    } else {
                                        privileageGive.setStatus("0");
                                        levelPrivileageGiveMapper.updateById(privileageGive);
                                    }
                                }
                            } else {
                                LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                                Long customerPrivilegeUid = customerPrivilege.getCustomerPrivilegeUid();
                                levelPrivileageGive.setPrivileageId(customerPrivilegeUid);
                                levelPrivileageGive.setGiveGiftId(id);
                                levelPrivileageGive.setGiveType(privilegeName);
                                levelPrivileageGive.setCreateName(username);
                                levelPrivileageGive.setCreateUser(userId);
                                levelPrivileageGive.setCreateTime(date);
                                levelPrivileageGive.setStatus("1");
                                levelPrivileageGiveMapper.insert(levelPrivileageGive);
                            }
                        }
                        //修改
                        for (LevelPrivileageGiveVo privileageGiveVo : levelPrivileageGives) {
                            Long givefiftId = privileageGiveVo.getGiveGiftId();
                            String giveType = privileageGiveVo.getGiveType();
                            QueryWrapper<LevelPrivileageGive> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("GIVE_GIFT_ID", givefiftId);
                            queryWrapper.eq("GIVE_TYPE", giveType);
                            queryWrapper.eq("PRIVILEAGE_ID", privileg.getCustomerPrivilegeUid());
                            queryWrapper.eq("STATUS", "1");
                            LevelPrivileageGive privileageGive = levelPrivileageGiveMapper.selectOne(queryWrapper);
                            LevelPrivileageGive levelPrivileageGive = new LevelPrivileageGive();
                            if (privileageGive != null) {
                                levelPrivileageGive.setGiveId(privileageGive.getGiveId());
                                levelPrivileageGive.setPrivileageId(privileg.getCustomerPrivilegeUid());
                                levelPrivileageGive.setGiveGiftId(privileageGiveVo.getGiveGiftId());
                                levelPrivileageGive.setGiveType(privileageGiveVo.getGiveType());
                                levelPrivileageGive.setGiveName(privileageGiveVo.getGiveName());
                                levelPrivileageGive.setGiveSumNumber(privileageGiveVo.getGiveSumNumber());
                                levelPrivileageGive.setGiveNumber(privileageGiveVo.getGiveNumber());
                                levelPrivileageGive.setCreateTime(privileageGive.getCreateTime());
                                levelPrivileageGive.setCreateName(privileageGive.getCreateName());
                                levelPrivileageGive.setCreateUser(privileageGive.getCreateUser());
                                levelPrivileageGive.setUpdateName(SecurityUtils.getUsername());
                                levelPrivileageGive.setUpdateUser(SecurityUtils.getUserId());
                                levelPrivileageGive.setUpdateTime(DateUtil.date());
                                levelPrivileageGive.setStatus(privileageGive.getStatus());
                                levelPrivileageGiveMapper.updateById(levelPrivileageGive);
                            } else {
                                levelPrivileageGive.setPrivileageId(privileg.getCustomerPrivilegeUid());
                                levelPrivileageGive.setGiveGiftId(givefiftId);
                                levelPrivileageGive.setGiveType(giveType);
                                levelPrivileageGive.setGiveName(privileageGiveVo.getGiveNumber());
                                levelPrivileageGive.setGiveSumNumber(privileageGiveVo.getGiveSumNumber());
                                levelPrivileageGive.setGiveNumber(privileageGiveVo.getGiveNumber());
                                levelPrivileageGive.setCreateTime(date);
                                levelPrivileageGive.setCreateName(username);
                                levelPrivileageGive.setCreateUser(userId);
                                levelPrivileageGive.setStatus(DataStatus.valid.getKey());
                                levelPrivileageGiveMapper.insert(levelPrivileageGive);
                            }
                        }
                    } else {
                        QueryWrapper<LevelPrivileageGive> queryWrappergive = new QueryWrapper<>();
                        queryWrappergive.eq("PRIVILEAGE_ID", privileg.getCustomerPrivilegeUid());
                        queryWrappergive.eq("GIVE_TYPE", privilegeName);
                        List<LevelPrivileageGive> PrivileageGive = levelPrivileageGiveMapper.selectList(queryWrappergive);
                        for (LevelPrivileageGive give : PrivileageGive) {
                            give.setStatus(DataStatus.invalid.getKey());
                            levelPrivileageGiveMapper.updateById(give);
                        }
                    }
                }
            } else {
                if ("true".equals(customerPrivilege.getPrivilegeStatus())) {
                    CustomerPrivilege cprivilege = new CustomerPrivilege();
                    cprivilege.setPlatformId(SecurityUtils.getPlatformId());
                    cprivilege.setPrivilegeUid(customerPrivilege.getPrivleageId());
                    cprivilege.setLevelUid(customerLevelVo.getLevelId());
                    cprivilege.setPrivilegeValue(customerPrivilege.getPrivilegeValue());
                    cprivilege.setPrivilegeStatus("1");
                    cprivilege.setCreateTime(DateUtil.date());
                    cprivilege.setCreateName(SecurityUtils.getUsername());
                    cprivilege.setCreateUser(SecurityUtils.getUserId());
                    cprivilege.setDataStatus("1");
                    customerPrivilegeService.save(cprivilege);
                    LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(customerPrivilege.getPrivleageId());
                    if (!"1".equals(levelPrivilege.getPrivilegeStatus())) {
                        levelPrivilege.setPrivilegeStatus("1");
                        levelPrivilegeMapper.updateById(levelPrivilege);
                    }
                } else {
                    CustomerPrivilege privilege = customerPrivilegeMapper.selectById(customerPrivilege.getCustomerPrivilegeUid());
                    if (privilege != null) {
                        privilege.setPrivilegeStatus("0");
                        customerPrivilegeMapper.updateById(privilege);
                    }
                }
            }
        }
        //判断业绩,最小积分,粉丝数是否发生变化,变化后更新客户绑定等级信息
        if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(customerLevelVo.getCustomerPattern())) {
            if (!level.getMinScore().equals(customerLevelVo.getMinScore()) || !level.getPerformance().equals(MoneyUtils.changeY2B(customerLevelVo.getPerformance())) || !level.getFansNumber().equals(customerLevelVo.getFansNumber())) {
                //更新客户绑定等级信息
                if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(customerLevelVo.getCustomerPattern()) && CustomerLevelStartTypeEnum.start.getKey().equals(customerLevelVo.getStartStatus())) {
                    QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>();
                    customerInfoQueryWrapper.eq("PLATFORM_UID", platformId);
                    customerInfoQueryWrapper.ne("STATUS", DataStatus.delete.getKey());
                    customerInfoQueryWrapper.select("CUSTOMER_UID");
                    List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(customerInfoQueryWrapper);
                    for (CustomerInfo info : customerInfoList) {
                        QueryWrapper<CustomerFund> customerFundQueryWrapper = new QueryWrapper<>();
                        customerFundQueryWrapper.eq("CUSTOMER_UID", info.getCustomerUid());
                        CustomerFund customerFund = customerFundMapper.selectOne(customerFundQueryWrapper);
                        if (customerFund != null) {
                            if (customerFund.getAllProfit() >= Long.parseLong(String.valueOf(customerLevel.getPerformance()))
                                    && customerFund.getAllScore() > customerLevel.getMinScore()
                                    && customerFund.getAllFans() + customerFund.getAllFansSecond() >= customerLevel.getFansNumber()) {
                                //满足条件绑定等级
                                bindFreeLevel(info.getCustomerUid(), customerLevelVo.getLevelId());
                            } else {
                                //未满足条件解绑等级
                                setBindLevelInvalid(info.getCustomerUid());
                            }
                        }
                    }
                }
                //更新等级客户数
                updateLevelCustoemrCount(customerLevelVo.getLevelId());
            }
        }
        return true;
    }

    /**
     * 绑定客户等级 新
     *
     * @param customerUid
     * @param levelUId
     */
    public void bindFreeLevelNew(Long customerUid, Long levelUId, CustomerFund fund) {
        //判断当前客户是否绑定等级
        /*
        QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
        levelInfoQueryWrapper.eq("CUSTOMER_UID", customerUid);
        levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        List<CustomerLevelInfo> customerLevelInfoList = customerLevelInfoMapper.selectList(levelInfoQueryWrapper);
        if (customerLevelInfoList != null && customerLevelInfoList.size() > 0) {
            for (CustomerLevelInfo customerLevelInfo : customerLevelInfoList) {
                //判断只绑定免费等级并且不等于当前等级
                CustomerLevel levelInfo = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                //关系表只存在一条并且不是免费客户等级
                if (customerLevelInfoList.size() == 1 && !CustomerLevelPatternTypeEnum.freeMode.getKey().equals(levelInfo.getCustomerPattern())) {
                    saveCustoemrLevelRelation(customerUid, levelUId, fund.getProfit());
                } else {
                    if (!customerLevelInfo.getLevelUid().equals(levelUId)) {
                        if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(levelInfo.getCustomerPattern())) {
                            //绑定过等级,设置成无效
                            customerLevelInfo.setStatus(DataStatus.delete.getKey());
                            customerLevelInfoMapper.updateById(customerLevelInfo);
                            saveCustoemrLevelRelation(customerUid, levelUId, fund.getProfit());
                        }
                    }
                }
            }
        } else {
            saveCustoemrLevelRelation(customerUid, levelUId, fund.getProfit());
        }*/
    }

    //绑定等级信息
    public void bindFreeLevel(Long customerUid, Long levelUId) {
        //判断当前客户是否绑定等级
        /*
        QueryWrapper<CustomerLevelInfo> levelInfoQueryWrapper = new QueryWrapper<>();
        levelInfoQueryWrapper.eq("CUSTOMER_UID", customerUid);
        levelInfoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        List<CustomerLevelInfo> customerLevelInfoList = customerLevelInfoMapper.selectList(levelInfoQueryWrapper);
        if (customerLevelInfoList != null && customerLevelInfoList.size() > 0) {
            for (CustomerLevelInfo customerLevelInfo : customerLevelInfoList) {
                //判断只绑定免费等级并且不等于当前等级
                CustomerLevel levelInfo = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                //关系表只存在一条并且不是免费客户等级
                if (customerLevelInfoList.size() == 1 && !CustomerLevelPatternTypeEnum.freeMode.getKey().equals(levelInfo.getCustomerPattern())) {
                    saveCustoemrLevelRelation(customerUid, levelUId, 0L);
                } else {
                    if (!customerLevelInfo.getLevelUid().equals(levelUId)) {
                        if (CustomerLevelPatternTypeEnum.freeMode.getKey().equals(levelInfo.getCustomerPattern())) {
                            //绑定过等级,设置成无效
                            customerLevelInfo.setStatus(DataStatus.delete.getKey());
                            customerLevelInfoMapper.updateById(customerLevelInfo);
                            saveCustoemrLevelRelation(customerUid, levelUId, 0L);
                        }
                    }
                }
            }
        } else {
            saveCustoemrLevelRelation(customerUid, levelUId, 0L);
        }*/
    }

    //设置更改等级无效
    public void setBindLevelInvalid(Long customerUid) {

    }


    @Override
    public Long getLevelInfoListCount(CustomerLeveListlVo customerLevelVo) {
        Long PlatformUid = SecurityUtils.getPlatformId();
        return customerLevelMapper.getLevelInfoListCount(PlatformUid);
    }

    @Override
    public Long getPayLevelInfoListCount(CustomerLeveListlVo customerLevelVo) {
        Long PlatformUid = SecurityUtils.getPlatformId();
        return customerLevelMapper.getPayLevelInfoListCount(PlatformUid);
    }

    @Override
    public List<CustomerLevelPrivleageVo> getLevelPrivileageInfo() {
        List<CustomerLevelPrivleageVo> customerLevelPrivleageVoList = new ArrayList<>();
        List<LevelPrivilege> levelPrivileges = levelPrivilegeService.getprivilegeInfoList();
        for (LevelPrivilege levelPrivilege : levelPrivileges) {
            CustomerLevelPrivleageVo privleageVo = new CustomerLevelPrivleageVo();
            privleageVo.setPrivleageShowName(levelPrivilege.getPrivilegeShowname());
            privleageVo.setPrivleageName(levelPrivilege.getPrivilegeName());
            privleageVo.setIsUpgrade(levelPrivilege.getIsUpgrade());
            privleageVo.setPrivleageId(levelPrivilege.getPrivilegeUid());
            privleageVo.setCustomerPrivilegeUid(0L);
            privleageVo.setPrivilegeStatus(false);
            privleageVo.setPrivilegeValue(null);
            privleageVo.setPlatformUnit(levelPrivilege.getPlatformUnit());
            privleageVo.setIsGive(levelPrivilege.getIsGiveType());
            privleageVo.setDiscountCouponList(null);
            privleageVo.setGiftList(null);
            customerLevelPrivleageVoList.add(privleageVo);
        }
        return customerLevelPrivleageVoList;
    }

    @Override
    public List<PaymentRuleVo> getPaymentRuleInfo() {
        List<PaymentRuleVo> paymentRuleVoList = new ArrayList<>();
        PaymentRuleVo paymentRuleVo = new PaymentRuleVo();
        paymentRuleVoList.add(paymentRuleVo);
        return paymentRuleVoList;
    }

    /**
     * 查询付费等级列表
     *
     * @return
     */
    @Override
    public List<CustomerLevel> getPayLevelInfo() {
        QueryWrapper<CustomerLevel> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("CUSTOMER_PATTERN","1");
        queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("START_STATUS", DataStatus.valid.getKey());
        queryWrapper.orderByAsc("customer_Grade");
        List<CustomerLevel> customerLevelList = customerLevelMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(customerLevelList)) {
            for (CustomerLevel level : customerLevelList) {
                //查询折扣的权益
                LevelPrivilege levelPrivilege = levelPrivilegeService.selectByName(CustomerLevelPrivilegeEnum.discount.getKey());
                if (ObjectUtil.isNotEmpty(levelPrivilege)) {
                    QueryWrapper<CustomerPrivilege> queryWrappers = new QueryWrapper<>();
                    queryWrappers.eq("data_status", DataStatus.valid.getKey());
                    queryWrappers.eq("LEVEL_UID", level.getLevelId());
                    queryWrappers.eq("PRIVILEGE_UID", levelPrivilege.getPrivilegeUid());
                    queryWrappers.last(" order by CUSTOMER_PRIVILEGE_UID desc limit 1");
                    CustomerPrivilege privilege = customerPrivilegeMapper.selectOne(queryWrappers);
                    if (ObjectUtil.isNotEmpty(privilege)) {
                        level.setLevelValue(privilege.getPrivilegeValue());
                    }
                }
            }
        }


        return customerLevelList;
    }


    /**
     * 查询会员及权益信息
     */
    @Override
    public List<CustomerLevelOpenVo> getCustomerLevelInfo() {
        Long customerPlatformUid = SecurityUtils.getCustomerPlatformUid();
        logger.info("开始查询{}：平台等级信息", customerPlatformUid);
        CustomerLevelInfo bindLevelInfo = getBindLevelInfo();
        List<CustomerLevelOpenVo> customerLevelVoList = customerLevelMapper.selectCustomerLevelPrivilegeInfo(customerPlatformUid);
        for (CustomerLevelOpenVo levelVo : customerLevelVoList) {
            List<CustomerPrivilegeOpenVo> CustomerRightsInterestsList = new ArrayList<>();
            List<CustomerPrivilegeOpenVo> CustomerGiftBagList = new ArrayList<>();
            List<CustomerPrivilegeOpenVo> customerPrivileges = levelVo.getCustomerPrivileges();
            for (CustomerPrivilegeOpenVo privilegeVo : customerPrivileges) {
                if (privilegeVo.getCustomerPrivlege() != null) {
                    //普通权益
                    String privilegeValue = privilegeVo.getPrivilegeValue();
                    String platformUnit = privilegeVo.getPlatformUnit();
                    if (!StringUtils.isEmpty(privilegeValue)) {
                        privilegeVo.setPrivilegeValue(privilegeValue + platformUnit);
                    }
                    CustomerRightsInterestsList.add(privilegeVo);
                }
                if (privilegeVo.getUpgradeGiftBag() != null) {
                    //升级礼包
                    String privilegeValue = privilegeVo.getPrivilegeValue();
                    String platformUnit = privilegeVo.getPlatformUnit();
                    if (!StringUtils.isEmpty(platformUnit) && !CustomerLevelPrivilegeEnum.gift.getValue().equals(privilegeValue)) {
                        privilegeVo.setPrivilegeValue(privilegeValue + platformUnit);
                    }
                    if (CustomerPrivilegeValEnum.freeGift.getValue().equals(privilegeValue)) {
                        if (CustomerLevelPrivilegeEnum.gift.getKey().equals(privilegeVo.getPrivilegeName())) {
                            privilegeVo.setPlatformUnit("个");
                        }
                        if (CustomerLevelPrivilegeEnum.coupon.getKey().equals(privilegeVo.getPrivilegeName())) {
                            privilegeVo.setPlatformUnit("张");
                        }
                    }
                    CustomerGiftBagList.add(privilegeVo);
                    if ((CustomerPrivilegeValEnum.freeGift.getValue().equals(privilegeVo.getPrivilegeValue()))) {
                        String privilegeName = privilegeVo.getPrivilegeName();
                        Long customerPrivilegeUid = privilegeVo.getCustomerPrivilegeUid();
                        List<com.probox.customer.api.domain.LevelPrivileageGiveVo> levelPrivileageGives = levelPrivileageGiveMapper.selectPrivileageGiveList(privilegeName, customerPrivilegeUid);
                        for (com.probox.customer.api.domain.LevelPrivileageGiveVo giveVo : levelPrivileageGives) {
                            if (CustomerLevelPrivilegeEnum.gift.getKey().equals(giveVo.getGiveType())) {

                            } else if (CustomerLevelPrivilegeEnum.coupon.getKey().equals(giveVo.getGiveType())) {
                                ActivityCouponVo coupon = getCouponById(giveVo.getGiveGiftId());
                                //更新优惠券总数
                                if (coupon != null) {
                                    giveVo.setGiveSumNumber(String.valueOf(coupon.getCouponNums()));
                                    giveVo.setGiveGiftId(coupon.getCouponUid());
                                    giveVo.setGiveName(coupon.getCouponName());
                                    giveVo.setGiveType(CustomerLevelPrivilegeEnum.coupon.getValue());
                                }
                            } else {
                                return null;
                            }

                        }
                        privilegeVo.setLevelPrivileageGives(levelPrivileageGives);
                    }
                }
            }

            levelVo.setCustomerRightsInterests(CustomerRightsInterestsList);
            levelVo.setCustomerGiftBag(CustomerGiftBagList);
            levelVo.setCustomerPrivileges(null);
            //判断购买状态
            Long customerUid = SecurityUtils.getCustomerUid();
            if (customerUid == null && CustomerLevelPatternTypeEnum.payMode.getKey().equals(levelVo.getCustomerPattern())) {
                levelVo.setPurchaseType(CustomerPurchaseTypeEnum.purchasable.getKey());
            }
            if (bindLevelInfo != null) {
                CustomerLevel customerLevel = customerLevelMapper.selectById(bindLevelInfo.getLevelUid());
                if (customerLevel != null) {
                    if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevel.getCustomerPattern())) {
                        if (customerLevel.getCustomerGrade() > levelVo.getCustomerGrade()) {
                            levelVo.setPurchaseType(CustomerPurchaseTypeEnum.doNotBuy.getKey());
                        }
                        if (customerLevel.getCustomerGrade() < levelVo.getCustomerGrade()) {
                            levelVo.setPurchaseType(CustomerPurchaseTypeEnum.purchasable.getKey());
                        }
                        if (customerLevel.getCustomerGrade() == levelVo.getCustomerGrade()) {
                            levelVo.setPurchaseType(CustomerPurchaseTypeEnum.toRenew.getKey());
                        }
                    } else {
                        if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(levelVo.getCustomerPattern())) {
                            levelVo.setPurchaseType(CustomerPurchaseTypeEnum.purchasable.getKey());
                        }
                    }
                } else {
                    if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(levelVo.getCustomerPattern())) {
                        levelVo.setPurchaseType(CustomerPurchaseTypeEnum.purchasable.getKey());
                    }
                }
            } else {
                if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(levelVo.getCustomerPattern())) {
                    levelVo.setPurchaseType(CustomerPurchaseTypeEnum.purchasable.getKey());
                }
            }
            logger.info("查询会员及权益信息当前购买状态" + levelVo.getPurchaseType());
            //判断付费等级过期时间
            com.probox.customer.api.domain.PaymentRuleVo paymentRules = levelVo.getPaymentRules();
            if (paymentRules != null) {
                if (CustomerPurchaseTypeEnum.purchasable.getKey().equals(levelVo.getPurchaseType()) || CustomerPurchaseTypeEnum.doNotBuy.getKey().equals(levelVo.getPurchaseType())) {
                    logger.info("查询等级状态:可购买");
                    //可购买
                    Integer periodValidityNumber = paymentRules.getPeriodValidityNumber();
                    Date date = new Date();
                    Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, periodValidityNumber);
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString = formatter.format(newDate);
                    paymentRules.setExpireTime(dateString);
                    paymentRules.setPrice(MoneyUtils.changeF2B2(paymentRules.getPrice()));
                } else if (CustomerPurchaseTypeEnum.toRenew.getKey().equals(levelVo.getPurchaseType())) {
                    logger.info("查询等级状态:可续费");
                    //可续费
                    /*
                    QueryWrapper<CustomerLevelInfo> levelInfowrapp = new QueryWrapper<>();
                    levelInfowrapp.eq("CUSTOMER_UID", customerUid);
                    levelInfowrapp.eq("STATUS", DataStatus.valid.getKey());
                    List<CustomerLevelInfo> customerLevelInfoList = customerLevelInfoMapper.selectList(levelInfowrapp);
                    for (CustomerLevelInfo customerLevelInfo : customerLevelInfoList) {
                        CustomerLevel customerLevel = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                        if ("1".equals(customerLevel.getCustomerPattern())) {
                            Date expireTime = customerLevelInfo.getExpireTime();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateString = formatter.format(expireTime);
                            paymentRules.setExpireTime(dateString);
                            paymentRules.setPrice(MoneyUtils.changeF2B2(paymentRules.getPrice()));
                        }
                    }
                    */
                } else {
                    logger.info("查询等级状态不为续费或可购买,设置价格");
                    paymentRules.setPrice(MoneyUtils.changeF2B2(paymentRules.getPrice()));
                }


            }


        }

        return customerLevelVoList;
    }

    //判断当前客户绑定等级
    public CustomerLevelInfo getBindLevelInfo() {
        CustomerLevelInfo levelInfo = new CustomerLevelInfo();
        if (SecurityUtils.getCustomerUid() == null) {
            return levelInfo;
        }
        QueryWrapper<CustomerFund> fundQueryWrapper = new QueryWrapper<>();
        fundQueryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        CustomerFund customerFund = customerFundMapper.selectOne(fundQueryWrapper);
        List<CustomerLevelInfo> customerBindLevelInfoList = customerLevelInfoService.getCustomerBindLevelInfo(SecurityUtils.getCustomerUid(), customerFund.getFundUid(), SecurityUtils.getCustomerPlatformUid());
        if (customerBindLevelInfoList.size() > 1) {
            for (CustomerLevelInfo customerLevelInfo : customerBindLevelInfoList) {
                CustomerLevel customerLevel = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevel.getCustomerPattern())) {
                    levelInfo = customerLevelInfo;
                }
            }
        } else if (customerBindLevelInfoList.size() == 1) {
            levelInfo = customerBindLevelInfoList.get(0);
        }
        return levelInfo;
    }

    @Override
    public Integer getCustomerLevelInfoCount() {
        Long customerPlatformUid = SecurityUtils.getCustomerPlatformUid();
        List<CustomerLevelOpenVo> customerLevelVoList = customerLevelMapper.selectCustomerLevelPrivilegeInfo(customerPlatformUid);
        return customerLevelVoList.size();
    }

    /**
     * 根据等级id查询等级权益信息
     *
     * @param levelId
     * @return
     */
    @Override
    public CustomerLevelOpenVo getByCustomerLevelInfoID(Long levelId) {
        CustomerLevelOpenVo customerLevelVo = customerLevelMapper.selectByIdCustomerLevelPrivilegeInfo(levelId);
        if (customerLevelVo != null) {
            List<CustomerPrivilegeOpenVo> customerPrivileges = customerLevelVo.getCustomerPrivileges();
            for (CustomerPrivilegeOpenVo privilegeVo : customerPrivileges) {
                if ((CustomerPrivilegeValEnum.freeGift.getValue().equals(privilegeVo.getPrivilegeValue()))) {
                    String privilegeName = privilegeVo.getPrivilegeName();
                    Long customerPrivilegeUid = privilegeVo.getCustomerPrivilegeUid();
                    List<com.probox.customer.api.domain.LevelPrivileageGiveVo> levelPrivileageGives = levelPrivileageGiveMapper.selectPrivileageGiveList(privilegeName, customerPrivilegeUid);
                    for (com.probox.customer.api.domain.LevelPrivileageGiveVo giveVo : levelPrivileageGives) {
                        if (CustomerLevelPrivilegeEnum.gift.getKey().equals(giveVo.getGiveType())) {

                        } else if (CustomerLevelPrivilegeEnum.coupon.getKey().equals(giveVo.getGiveType())) {
                            ActivityCouponVo coupon = getCouponById(giveVo.getGiveGiftId());
                            //更新优惠券总数
                            if (coupon != null) {
                                giveVo.setGiveSumNumber(String.valueOf(coupon.getCouponNums()));
                                giveVo.setGiveGiftId(coupon.getCouponUid());
                                giveVo.setGiveName(coupon.getCouponName());
                                giveVo.setGiveType(CustomerLevelPrivilegeEnum.coupon.getValue());
                            }

                        } else {
                            return null;
                        }

                    }
                    privilegeVo.setLevelPrivileageGives(levelPrivileageGives);
                }
            }
            com.probox.customer.api.domain.PaymentRuleVo paymentRules = customerLevelVo.getPaymentRules();
            if (paymentRules != null) {
                paymentRules.setPrice(MoneyUtils.changeF2B2(paymentRules.getPrice()));
            }
        }
        return customerLevelVo;
    }

    @Override
    public void updateLevelCustoemrCount(Long levelId) {
        /*
        //更新等级客户数量
        QueryWrapper<CustomerLevelInfo> customerLevelInfoQueryWrapper = new QueryWrapper<>();
        customerLevelInfoQueryWrapper.eq("LEVEL_UID", levelId);
        customerLevelInfoQueryWrapper.ne("STATUS", DataStatus.delete.getKey());
        Integer customerCount = customerLevelInfoMapper.selectCount(customerLevelInfoQueryWrapper);
        CustomerLevel level = customerLevelMapper.selectById(levelId);
        level.setCustomerNumber(Long.parseLong(String.valueOf(customerCount)));
        customerLevelMapper.updateById(level);

         */
    }

    /**
     * 赠送等级升级礼包
     */

    public void giveLevelUpgradeGiftBag(Long custoemrUid, Long platformUid, Long levelUid) {

        CustomerInfo info = customerInfoMapper.selectById(custoemrUid);
        List<com.probox.customer.api.domain.CustomerInfoVo> customerInfoVoList = new ArrayList<>();
        com.probox.customer.api.domain.CustomerInfoVo customerInfoVo = new com.probox.customer.api.domain.CustomerInfoVo();
        customerInfoVo.setCustomerUid(info.getCustomerUid());
        customerInfoVo.setCustomerName(info.getCustomerName());
        customerInfoVo.setHeadImage(info.getHeadImage());
        customerInfoVoList.add(customerInfoVo);

        QueryWrapper<CustomerPrivilege> privilegeQueryWrapper = new QueryWrapper<>();
        privilegeQueryWrapper.eq("LEVEL_UID", levelUid);
        privilegeQueryWrapper.eq("PRIVILEGE_STATUS", DataStatus.valid.getKey());
        privilegeQueryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        privilegeQueryWrapper.eq("IS_UPGRADE", DataStatus.invalid.getKey());
        List<CustomerPrivilege> customerPrivileges = customerPrivilegeMapper.selectList(privilegeQueryWrapper);
        List<Long> gives = new ArrayList<>();
        for (CustomerPrivilege customerPrivilege : customerPrivileges) {
            LevelPrivilege levelPrivilege = levelPrivilegeMapper.selectById(customerPrivilege.getPrivilegeUid());
            if (ObjectUtil.isNotEmpty(levelPrivilege)) {
                if (CustomerLevelPrivilegeEnum.coupon.getKey().equals(levelPrivilege.getPrivilegeName())) {
                    gives.add(customerPrivilege.getCustomerPrivilegeUid());
                } else if (CustomerLevelPrivilegeEnum.item.getKey().equals(levelPrivilege.getPrivilegeName())) {
                    gives.add(customerPrivilege.getCustomerPrivilegeUid());
                } else if (CustomerLevelPrivilegeEnum.good.getKey().equals(levelPrivilege.getPrivilegeName())) {
                    gives.add(customerPrivilege.getCustomerPrivilegeUid());
                } else if (CustomerLevelPrivilegeEnum.proboxCard.getKey().equals(levelPrivilege.getPrivilegeName())) {
                    gives.add(customerPrivilege.getCustomerPrivilegeUid());
                } else if (CustomerLevelPrivilegeEnum.points.getKey().equals(levelPrivilege.getPrivilegeName())) {
                    //送积分
                    com.probox.customer.api.domain.CustomerFundVo customerFundVo = new com.probox.customer.api.domain.CustomerFundVo();
                    customerFundVo.setCustomerUid(custoemrUid);
                    customerFundVo.setPlatformUid(platformUid);
                    customerFundVo.setScore(Long.parseLong(customerPrivilege.getPrivilegeValue()));
                    customerFundVo.setStatus(DataStatus.valid.getKey());
                    customerFundVo.setRemark("升级等级赠送");
                    customerFundVo.setBizTime(new Date());
                    customerFundService.addCustomerFund(customerFundVo);
                }
            }
        }
        if (gives.size() > 0) {
            //送优惠券
            CouponQuery couponQuery = new CouponQuery();
            List<Long> couponID = new ArrayList<>();
            QueryWrapper<LevelPrivileageGive> privileageGiveQueryWrapper = new QueryWrapper<>();
            privileageGiveQueryWrapper.in("PRIVILEAGE_ID", gives);
            privileageGiveQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
            List<LevelPrivileageGive> levelPrivileageGives = levelPrivileageGiveMapper.selectList(privileageGiveQueryWrapper);

            for (LevelPrivileageGive privileageGive : levelPrivileageGives) {
                if (privileageGive.getGiveType().equals(CustomerLevelPrivilegeEnum.coupon.getKey())) {

                } else if (privileageGive.getGiveType().equals(CustomerLevelPrivilegeEnum.proboxCard.getKey())) {

                } else if (privileageGive.getGiveType().equals(CustomerLevelPrivilegeEnum.item.getKey())) {

                } else if (privileageGive.getGiveType().equals(CustomerLevelPrivilegeEnum.good.getKey())) {

                }
            }
        }
    }


    /**
     * 判断传入的两个数组有哪些值不同
     *
     * @param t1
     * @param t2
     * @param <T>
     * @return
     */
    public static <T> List<T> compare(T[] t1, T[] t2) {
        List<T> list1 = Arrays.asList(t1);
        List<T> list2 = new ArrayList<T>();
        for (T t : t2) {
            if (!list1.contains(t)) {
                list2.add(t);
            }
        }
        if (t2.length == 0) {
            for (int i = 0; i < t1.length; i++) {
                list2.add(t1[i]);
            }
        }
        return list2;
    }

    public BigDecimal changeF2B2(BigDecimal poins) {
        BigDecimal Hundred = new BigDecimal("100");
        return poins.divide(Hundred, 3, RoundingMode.HALF_UP);
    }

    /**
     * 根据ID获取优惠券信息
     *
     * @param couponUid
     * @return
     */
    private ActivityCouponVo getCouponById(Long couponUid) {
       return null;
    }

    /**
     * 获取可以选择的等级
     *
     * @param levelId
     * @return
     */
    @Override
    public List<SysDictData> getLevel(Long levelId) {
        return customerLevelMapper.getLevel(levelId);
    }


}
